package com.example.eventbusdemo.controller;

import com.example.eventbusdemo.annotation.ObServerType;
import com.example.eventbusdemo.observer.RegObserver;
import com.example.eventbusdemo.service.UserService;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author: zhangQi
 * @Date: 2020-10-07 19:05
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    private List<RegObserver> regObservers = new ArrayList<>();

    @PostConstruct
    public void setRegObservers() throws Exception{
        //反射,指明扫描路径
        Reflections reflections = new Reflections("com.example.eventbusdemo.observer");
        //获取
        Set<Class<?>> classList = reflections.getTypesAnnotatedWith(ObServerType.class);
        for(Class clazz:classList){
            RegObserver observer = (RegObserver) Class.forName(clazz.getCanonicalName()).newInstance();
            //放入
            regObservers.add(observer);
        }
    }

    @PostMapping("/register")
    public Long register(String telephone,String password){
        /**
         * 省略校验参数 try-catch等
         */
        long userId = userService.register(telephone, password);
        for (RegObserver observer : regObservers){
            observer.handleRegSuccess(userId);
        }
        return userId;
    }

}
